const Comment = require('../models/Comment');
const Post = require('../models/Post');

// 创建评论
const createComment = async (req, res) => {
  try {
    const { content, postId, parentCommentId } = req.body;
    
    // 检查文章是否存在
    const post = await Post.findById(postId);
    if (!post) {
      return res.status(404).json({ message: '文章不存在' });
    }

    // 如果是回复评论，检查父评论是否存在
    if (parentCommentId) {
        // 查找父评论，并确保它属于同一篇文章且未被删除
        const parentComment = await Comment.findOne({
            _id: parentCommentId,
            post: postId,        // 确保父评论属于同一篇文章
            status: 'active'     // 确保父评论未被删除
        });
    
        if (!parentComment) {
            return res.status(404).json({ 
                message: '父评论不存在或已被删除' 
            });
        }
    }

    const comment = await Comment.create({
      content,
      post: postId,
      author: req.user._id,
      parentComment: parentCommentId
    });

    // 填充作者信息
    await comment.populate('author', 'username');
    
    res.status(201).json(comment);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 获取文章的所有评论
const getComments = async (req, res) => {
    try {
      const { postId } = req.params;
      const { page = 1, limit = 10 } = req.query;
  
      const comments = await Comment.find({ 
        post: postId,
        parentComment: null,  // 只获取顶级评论
        status: 'active'
      })
      .populate('author', 'username')
      .sort({ createdAt: -1 })
      .limit(limit * 1)
      .skip((page - 1) * limit);
  
      // 获取每个评论的回复
      const commentsWithReplies = await Promise.all(
        comments.map(async (comment) => {
          const replies = await Comment.find({
            parentComment: comment._id,
            status: 'active'
          })
          .populate('author', 'username')
          .sort({ createdAt: 1 })
          .limit(5);
  
          return {
            ...comment.toObject(),
            replies
          };
        })
      );
  
      const count = await Comment.countDocuments({ 
        post: postId,
        parentComment: null,
        status: 'active'
      });
  
      res.json({
        comments: commentsWithReplies,
        totalPages: Math.ceil(count / limit),
        currentPage: page
      });
    } catch (error) {
      res.status(500).json({ message: error.message });
    }
  };

// 更新评论
const updateComment = async (req, res) => {
  try {
    const { content } = req.body;
    const comment = await Comment.findById(req.params.id);
    
    if (!comment) {
      return res.status(404).json({ message: '评论不存在' });
    }

    // 检查是否是评论作者
    if (comment.author.toString() !== req.user._id.toString() && req.user.role !== 'admin') {
      return res.status(403).json({ message: '没有权限修改此评论' });
    }

    const updatedComment = await Comment.findByIdAndUpdate(
      req.params.id,
      { content },
      { new: true }
    ).populate('author', 'username');

    res.json(updatedComment);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 删除评论
const deleteComment = async (req, res) => {
  try {
    const comment = await Comment.findById(req.params.id);
    
    if (!comment) {
      return res.status(404).json({ message: '评论不存在' });
    }

    // 检查是否是评论作者或管理员
    if (comment.author.toString() !== req.user._id.toString() && req.user.role !== 'admin') {
      return res.status(403).json({ message: '没有权限删除此评论' });
    }

    // 软删除评论
    await Comment.findByIdAndUpdate(req.params.id, { status: 'deleted' });
    res.json({ message: '评论已删除' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

module.exports = {
  createComment,
  getComments,
  updateComment,
  deleteComment
};